package cn.edu.nuc.crm.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cn.edu.nuc.crm.dto.PageInfo;
import cn.edu.nuc.crm.entity.Account;
import cn.edu.nuc.crm.entity.Application;
import cn.edu.nuc.crm.entity.Manager;
import cn.edu.nuc.crm.entity.Product;
import cn.edu.nuc.crm.entity.Repay;
import cn.edu.nuc.crm.entity.Repayment;
import cn.edu.nuc.crm.entity.Sysfunction;
import cn.edu.nuc.crm.service.interfaces.AccountService;
import cn.edu.nuc.crm.service.interfaces.AdminService;
import cn.edu.nuc.crm.service.interfaces.ApplicationService;
import cn.edu.nuc.crm.service.interfaces.ManagerService;
import cn.edu.nuc.crm.service.interfaces.RepayService;
import cn.edu.nuc.crm.service.interfaces.RepaymentService;
import cn.edu.nuc.crm.service.interfaces.RoleService;
import cn.edu.nuc.crm.service.interfaces.SysfunctionService;


@Controller
public class ApplicationController {
	@Autowired
	private ApplicationService applicationService;
	@Autowired
	private RepaymentService repaymentService;
	@Autowired
	private RepayService repayService;
	
	@RequestMapping(value="/applicationlist",method=RequestMethod.GET)
	public String select(@RequestParam(name="current",defaultValue="1") int current,
			HttpSession session, Model model){	
		try {
			if(session.getAttribute("man")!=null){
				Manager manager = (Manager) session.getAttribute("man");
				int i = manager.getPositionid();
				PageInfo pi = new PageInfo();
						
				if(i == 1){
					pi = applicationService.piStatus(current,i);
					session.setAttribute("pi", pi);	
				}
				if(i == 2){
					pi = applicationService.piStatus(current,i);
					session.setAttribute("pi", pi);	
				}
				if(i == 3){
					pi = applicationService.piStatus(current,i);
					session.setAttribute("pi", pi);	
				}
				if(i == 4){
					pi = applicationService.piStatus(current,i);
					session.setAttribute("pi", pi);	
				}
				if(i == 5){
				    pi = applicationService.pi(current);
					session.setAttribute("pi", pi);	
				}

				
				//根据不同的  positionid去选择 不同的页面  
				switch (i){ 
				case 1 : return "application/applicationlistFksh";  
				case 2 : return "application/applicationlistCwsh";  
				case 3 : return "application/applicationlistDysh"; 
				case 4 : return "application/applicationlistYwzgsh";  
				case 5 : return "application/applicationlist"; 
				default : return "application/applicationlist"; 
				} 
			}
			if(session.getAttribute("ad")!=null){
				PageInfo pi = new PageInfo();
				pi = applicationService.pi(current);
				session.setAttribute("pi", pi);	
				return "application/applicationlist";
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "redirect:login";
	}
	/**
	 * 贷款申请查询
	 * @return
	 */
	@RequestMapping(value="/applicationsearch",method=RequestMethod.POST)
	public String search(Model model,String aptTrueName,HttpSession session){
		if( aptTrueName != null && !aptTrueName.equals("") ){
			List<Application> list = applicationService.selectByName(aptTrueName);
			session.setAttribute("pi", list);
			if(session.getAttribute("man")!=null){
				Manager manager = (Manager) session.getAttribute("man");
				int i = manager.getPositionid();
				switch (i){
				case 1 : return "application/searchFk";  
				case 2 : return "application/searchCw";  
				case 3 : return "application/searchDy"; 
				case 4 : return "application/searchYw";  
				case 5 : return "application/search"; 
				default : return "application/search"; 
			}
			
			}
		}
		return "application/search";	
	}
	/**
	 * 编辑
	 * @return
	 */
	
	 @RequestMapping(value="/applicationedit",method=RequestMethod.GET)
	public String update(Integer aptId,HttpSession session){
		 Application application=applicationService.selectByPrimaryKey(aptId);
		session.setAttribute("item",application);
		
		Manager manager = (Manager) session.getAttribute("man");
		int i = manager.getPositionid();
		switch (i){ 
		case 1 : return "application/editFksh";  
		case 2 : return "application/editCwsh";  
		case 3 : return "application/editDysh"; 
		case 4 : return "application/editYwzgsh";  
		case 5 : return "application/edit"; 
		default : return "application/edit"; 
		} 
		
	}
	 /**
	 * 删除申请
	 * @return
	 */
	@RequestMapping(value="/applicationdelete",method=RequestMethod.GET)
	public String delete(Integer aptId,HttpSession session){
		int result=applicationService.deleteByPrimaryKey(aptId);
		if(result>0){	
			return "/success1";	
			}else{
			session.setAttribute("info", "该产品不能删除");
			return "/productlist";
		}
	}	
	/**
	 * 
	 */
	@RequestMapping(value="/application",method=RequestMethod.GET)
	public String select(HttpSession session, Model model){	

		return "account/home";
	}
	@RequestMapping(value="/applicationsave",method=RequestMethod.POST)
	public String search(HttpSession session,Application application){
		if( application != null  ){
			if(application.getAptStatus() == 5){
				
				Repayment repayment = new Repayment();
				
				repayment.setAccountId(application.getAccountId());
				repayment.setAccountTruename(application.getAptTrueName());
				repayment.setRepaymentPlan(application.getAptRegplan());
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				repayment.setRepaymentTime(df.format(new Date()));
				repayment.setRepaymentUrges(0); // 0:还没有受理   等待审批   1：可以还款了  2：催促还款
				repayment.setRepaymentTotal(application.getAptTotal());
				repayment.setRepaymentTerminally(application.getAptTerminally());
				repayment.setAptId(application.getAptId());
				repaymentService.insert(repayment);
				
				Repay repay = new Repay();
				repay.setAccountId(application.getAccountId());
				repay.setAccountTruename(application.getAptTrueName());
				//存储的是申请单id，写错了，但是原理没错
				repay.setRepaymentId(application.getAptId());
				repay.setRepaymentPlan(application.getAptRegplan());
				repay.setRepaymentTerminally(application.getAptTerminally());
				repay.setRepaymentTotal(application.getAptTotal());
				repayService.insert(repay);
				
			}
			
			applicationService.update(application);
			return "redirect:/applicationlist";
		}
		return "redirect:/applicationlist";	
	}
	
	
	@RequestMapping(value="/applicationExport",method=RequestMethod.GET)
	public String export(HttpSession session,Application application,HttpServletRequest request,HttpServletResponse response){
		String excelName = "车贷贷款申请表.xls";
		String sheetName = "车贷贷款申请";
		List<Application> list = applicationService.findAll();
		try {
			this.generateExcel(list, excelName, sheetName,request,response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		return null;
	}
	
	public void generateExcel(List<Application> list, String excelName,
			String sheetName,HttpServletRequest request,HttpServletResponse response) throws Exception {
		// 文件生成到临时目录中
		String parentPath = request.getServletContext().getRealPath("")  
				+ "/excelTemplate/统计.xls";   //这个是我的excel模板  
		File pFile = new File(parentPath);
		if (!pFile.exists()) {
			pFile.mkdirs();
		}
		String filePath = parentPath + File.separator + System.nanoTime()
				+ ".xls";
		WritableWorkbook workbook = Workbook.createWorkbook(new File(filePath));
		WritableSheet sheet = workbook.createSheet(sheetName, 0);

		// 标题样式
		WritableFont titleFont = new WritableFont(WritableFont.TIMES, 12,
				WritableFont.NO_BOLD, false);
		titleFont.setColour(Colour.WHITE);
		WritableCellFormat titleStyle = new WritableCellFormat(titleFont);
		titleStyle.setBackground(Colour.LIGHT_BLUE);
		titleStyle.setBorder(Border.ALL, BorderLineStyle.THIN);
		titleStyle.setAlignment(Alignment.CENTRE);
		// 报表尾样式
		WritableFont toolFont = new WritableFont(WritableFont.TIMES, 11,
				WritableFont.NO_BOLD, false);
		toolFont.setColour(Colour.WHITE);
		WritableCellFormat toolStyle = new WritableCellFormat(toolFont);
		toolStyle.setBackground(Colour.LIGHT_BLUE);
		toolStyle.setBorder(Border.ALL, BorderLineStyle.THIN);
		toolStyle.setAlignment(Alignment.RIGHT);
		// 表格头样式
		WritableFont times16font = new WritableFont(WritableFont.TIMES, 11,
				WritableFont.NO_BOLD, false);
		times16font.setColour(Colour.WHITE);
		WritableCellFormat headStyle = new WritableCellFormat(times16font);
		headStyle.setBackground(Colour.LIGHT_BLUE);
		headStyle.setBorder(Border.ALL, BorderLineStyle.THIN);

		// 高亮行样式
		WritableFont highLigthRowFont = new WritableFont(WritableFont.TIMES,
				10, WritableFont.NO_BOLD, false);
		highLigthRowFont.setColour(Colour.BLACK);
		WritableCellFormat highLigthRowStyle = new WritableCellFormat(
				highLigthRowFont);
		highLigthRowStyle.setBackground(Colour.LIGHT_GREEN);
		highLigthRowStyle.setBorder(Border.ALL, BorderLineStyle.THIN);

		// 非高亮行样式
		WritableFont unHighLigthRowFont = new WritableFont(WritableFont.TIMES,
				10, WritableFont.NO_BOLD, false);
		unHighLigthRowFont.setColour(Colour.BLACK);
		WritableCellFormat unHighLigthRowStyle = new WritableCellFormat(
				unHighLigthRowFont);
		unHighLigthRowStyle.setBackground(Colour.WHITE);
		unHighLigthRowStyle.setBorder(Border.ALL, BorderLineStyle.THIN);
		// 设置Excel页签名字
		sheet.setName(sheetName);
		String[] cells = { "贷款申请编号", "贷款人姓名", "贷款时间","贷款状态 ", "汽车标价", "贷款金额", "汽车名称"
				,"还款计划","每期还款","还款总金额"
		        ,"风控审核", "风控审核意见", "财务审核", "财务审核意见 ", "抵押审核",
				"抵押审核意见", "业务主管审核", "业务主管审核意见","汇款确认","续保押金"};
		
		
		sheet.mergeCells(0, 0, cells.length - 1, 0);
		// 设置标题
		for (int m = 0; m < cells.length; m++) {
			sheet.addCell(new Label(0, 0, sheetName, titleStyle));
			sheet.addCell(new Label(m, 1, cells[m], headStyle));
			if (m == 0 || m == 5 || m == 8 || m == 10) {
				sheet.setColumnView(m, 30);// 设excel单元格的宽度
			} else {
				sheet.setColumnView(m, 15);// 设excel单元格的宽度
			}
		}
		int rowIndex = 2;
		// 循环遍历结果集
		for (int i = 0; i < list.size(); i++,rowIndex++) {
			
			Application ur = list.get(i);
			sheet.addCell(new Label(0, rowIndex, ur.getAptId().toString()));// 贷款申请编号
			sheet.addCell(new Label(1, rowIndex, ur.getAptTrueName()));// 贷款人姓名
			sheet.addCell(new Label(2, rowIndex, ur.getAptTime()));// 贷款时间
			if( ur.getAptStatus().toString()!= null){
				sheet.addCell(new Label(3, rowIndex, ur.getAptStatus().toString()));// 贷款状态
			}else{
				sheet.addCell(new Label(3, rowIndex, "未受理"));// 贷款状态
			}

			sheet.addCell(new Label(4, rowIndex, ur.getAptAmount()));// 汽车标价
			sheet.addCell(new Label(5, rowIndex, ur.getAptBuyCar()));//贷款金额


			sheet.addCell(new Label(6, rowIndex, ur.getAptCar()));//汽车名称


			sheet.addCell(new Label(7, rowIndex, ur.getAptRegplan()));//还款计划
			sheet.addCell(new Label(8, rowIndex, ur.getAptTerminally()));//每期还款
			sheet.addCell(new Label(9, rowIndex, ur.getAptTotal()));//还款总金额
			if(ur.getAptFksh()!=null){
				sheet.addCell(new Label(10, rowIndex, ur.getAptFksh().toString()));//风控审核
			}else{
				sheet.addCell(new Label(10, rowIndex, ""));//风控审核
			}
			
	
			
			if(ur.getAptFkshYj()!=null){
				sheet.addCell(new Label(11, rowIndex, ur.getAptFkshYj()));//风控审核意见
			}else{
				sheet.addCell(new Label(11, rowIndex, ""));//风控审核意见
			}
			
			if(ur.getAptCwsh()!=null){
				sheet.addCell(new Label(12, rowIndex, ur.getAptCwsh().toString()));// 财务审核
			}else{
				sheet.addCell(new Label(12, rowIndex, ""));// 财务审核
			}
			
			if(ur.getAptCwshYj()!=null){
				sheet.addCell(new Label(13, rowIndex, ur.getAptCwshYj()));// 财务审核意见
			}else{
				sheet.addCell(new Label(13, rowIndex, ""));// 财务审核意见
			}	
		
			if(ur.getAptDysh()!=null){
				sheet.addCell(new Label(14, rowIndex,ur.getAptDysh().toString()));// 抵押审核
			}else{
				sheet.addCell(new Label(14, rowIndex,""));// 抵押审核
			}
		
			if(ur.getAptDyshYj()!=null){
				sheet.addCell(new Label(15, rowIndex,ur.getAptDyshYj()));// 抵押审核意见
			}else{
				sheet.addCell(new Label(15, rowIndex,""));// 抵押审核意见
			}
			
			if(ur.getAptYwzgsh()!=null){
				sheet.addCell(new Label(16, rowIndex,ur.getAptYwzgsh().toString()));// 业务主管审核
			}else{
				sheet.addCell(new Label(16, rowIndex,""));// 业务主管审核
			}
			
			if(ur.getAptYwzgshYj()!=null){
				sheet.addCell(new Label(17, rowIndex,ur.getAptYwzgshYj()));// 业务主管审核意见
			}else{
				sheet.addCell(new Label(17, rowIndex,""));// 业务主管审核意见
			}
			
			if(ur.getAptAccountHkqr()!=null){
				sheet.addCell(new Label(18, rowIndex,ur.getAptAccountHkqr().toString()));// 汇款确认
			}else{
				sheet.addCell(new Label(18, rowIndex,"未确认"));// 汇款确认
			}
			
			if(ur.getAptAccountXbyj()!= null){
				sheet.addCell(new Label(19, rowIndex,ur.getAptAccountXbyj()));// 续保押金
			}else{
				sheet.addCell(new Label(19, rowIndex,""));// 续保押金
			}
			
		}
		// 获取总记录条数
		int totle = 0;
		if (list != null) {
			totle = list.size();
		}
		// 设置报表尾
		sheet.mergeCells(0, rowIndex, cells.length - 1, rowIndex);
		sheet.mergeCells(0, rowIndex + 1, cells.length - 1, rowIndex + 1);
		sheet.addCell(new Label(0, rowIndex + 1, "报告已完成  / 共计：" + totle
				+ " 条。 ", toolStyle));
		
		workbook.write();
		workbook.close();

		// <!-- 生成完毕-->

		// 下载生成的报表文件
		File xlsFile = new File(filePath);
		if (xlsFile.exists()) {
			response.setHeader("Content-Disposition", "attachment; filename="
					+ new String(excelName.getBytes("GBK"), "ISO8859-1")); // filename应该是编码后的(utf-8)
			response.setHeader("charset", "utf-8");
			response.setContentType("application/vnd.ms-excel");// 设置下载文件的格式，此处为msexcel
			OutputStream os = response.getOutputStream();
			InputStream is = new FileInputStream(xlsFile);
			byte[] tmp = new byte[1024];
			int len;
			while ((len = is.read(tmp)) != -1) {
				os.write(tmp, 0, len);
			}
			is.close();
			os.flush();
			os.close();
			// 下载完成后删除临时文件
			xlsFile.delete();
		}

	}
	
}
	
	
	
	

